/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.storage.android.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import de.fuberlin.replication.storage.Transaction;
import de.fuberlin.replication.storage.android.AndroidStorage;

/**
 * Android-specific SQLite replication metadata storage implementation.
 */
public class SQLiteStorage extends AndroidStorage {
	private SQLiteDatabaseHelper helper;

	private SQLiteSubsetDAO subsetDAO;
	private SQLiteMetadataDAO metadataDAO;

	/**
	 * @see AndroidStorage#AndroidStorage(Context)
	 */
	public SQLiteStorage(Context context) {
		super(context);
	}

	private SQLiteDatabaseHelper getHelper() {
		if (helper == null)
			helper = new SQLiteDatabaseHelper(getContext());

		return helper;
	}

	@Override
	public SQLiteSubsetDAO getSubsetDAO() {
		if (subsetDAO == null)
			subsetDAO = new SQLiteSubsetDAO(getHelper());

		return subsetDAO;
	}

	@Override
	public SQLiteMetadataDAO getMetadataDAO() {
		if (metadataDAO == null)
			metadataDAO = new SQLiteMetadataDAO(getHelper());

		return metadataDAO;
	}

	@Override
	public void runTransactional(Transaction transaction) {
		SQLiteDatabase db = getHelper().getWritableDatabase();

		db.beginTransaction();

		try {
			transaction.run(this);

			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	/**
	 * @see SQLiteOpenHelper#close()
	 */
	public void close() {
		if (helper != null)
			helper.close();
	}
}